package web.handler

import manager.AsyncTask
import manager.PayManager
import org.json.JSONObject
import web.request.jsonOf

open class OnPayHandler(json: JSONObject) : AbstractHandler(json, REQ) {

    companion object {

        const val REQ = "pay"

        const val FIELD_APPID = "appId"
        const val FIELD_PRICE = "price"
        const val FIELD_SUCCESS = "success"

        var payFlag = false
            private set

        var payAppId = ""

        fun setAppId(id: String) {
            payAppId = id
        }

        fun payCancel() {
            PayManager.onExit()
            payFlag = false
            self?.removeTimeout()
        }

        var self: OnPayHandler? = null
            private set
    }

    open fun begin() {
    }

    open fun onPaySuccess() {
    }

    override fun exec(): JSONObject {
        begin()

        if (payFlag) {
            throw IllegalStateException("Payment is already being requested")
        }
        payFlag = true
        self = this

        val resp = jsonOf("Start the payment", CODE_OK)

        val appId = json.getString(FIELD_APPID)
        val price = json.getDouble(FIELD_PRICE)

        setAppId(appId)

        AsyncTask.postDelayed(onTimeoutFunc, 60 * 1000)

        PayManager.payInWeb(price, ::payResult)

        resp.put(FIELD_APPID, appId)

        return resp
    }

    private fun payResult(flag: Boolean) {
        payFlag = false

        removeTimeout()

        val resp = jsonOf(MSG_OK, CODE_OK)

        resp.put(FIELD_APPID, payAppId)
        resp.put(FIELD_SUCCESS, flag)
        resp.put(FIELD_REQUEST, REQ)

        sendResponse(resp)

        if (flag) {
            onPaySuccess()
        }
    }

    private fun removeTimeout() {
        AsyncTask.removeCallbacks(onTimeoutFunc)
    }

    private fun onTimeout() {
        payFlag = false
        PayManager.onExit()

        val resp = jsonOf(MSG_TIMEOUT, CODE_TIMEOUT)

        resp.put(FIELD_APPID, payAppId)
        resp.put(FIELD_SUCCESS, false)
        resp.put(FIELD_REQUEST, REQ)

        sendResponse(resp)
    }

    private val onTimeoutFunc = object: Runnable {

        override fun run() {

            onTimeout()
        }
    }

}

